<script setup>
import InfoChart from "../components/InfoChart.vue";

import CityList from "../components/CityList.vue";

//导入api接口
import { getAdcodeByCityName, getAdcodeByIp, getWeatherByAdcode } from "@/apis";

// 路由配置
import { useRoute, useRouter } from "vue-router";
import { onMounted, ref } from "vue";
const route = useRoute();
const router = useRouter();

//输入框内容
const keyword = ref("");
//城市列表提示列表
const suggestList = ref([]);
//本地天气预报数据
const weatherInfo = ref({});

/**
 * 返回的数据有可能是省份，也有可能是城市，需要对数据进行格式化
 * @param {Array} data 原始数据
 */
const formatData = (data) => {
  const list = [];
  data.map((item) => {
    if (typeof item.city === "string" && item.city.includes(keyword.value)) {
      list.push({
        cityNmae: item.city,
        adcode: item.adcode,
      });
    } else if (
      typeof item.province === "string" &&
      item.province.includes(keyword.value)
    ) {
      list.push({
        cityNmae: item.province,
        adcode: item.adcode,
      });
    }
  });
  if (list.length === 0) {
    //没有匹配
    list.push({
      cityNmae: "似乎没有找到这个城市",
      adcode: "",
    });
  }
  return list;
};

const handleChange = async (e) => {
  keyword.value = e.target.value;
  // 搜索的时候清空提示列表
  suggestList.value = [];
  // 调用接口获取城市编码
  const res = await getAdcodeByCityName(keyword.value);
  // 处理城市列表提示列表
  if (res.status === "1") {
    suggestList.value = formatData(res.geocodes);
  }
};

//闭包+立即执行函数 做防抖处理，减少不必要的请求
const debouncedHandleChange = (function debounce(func, wait) {
  let timeout;
  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
})(handleChange, 500); //500ms的防抖时间

// 点击城市列表跳转到天气详情页面
const handleRoute = (adcode, cityName) => {
  if (adcode) {
    router.push({
      name: "info",
      query: { adcode, cityName },
    });
  }
};

onMounted(async () => {
  // 监听路由变化，更新城市列表
  // 获取当前页面的adcode
  const { adcode } = await getAdcodeByIp();
  // 根据adcode获取天气信息
  const data = await getWeatherByAdcode(adcode);
  weatherInfo.value = data.forecasts[0].casts;
});
</script>

<template>
  <!-- 搜索框 -->
  <div class="search pt-4 mb-8 relative">
    <input
      type="text"
      placeholder="请输入城市名称"
      class="py-2 px-1 w-full bg-transparent border-b focus:border-input-fcous focus:outline-none"
      :value.trim="keyword"
      @input="debouncedHandleChange"
    />
    <ul
      v-if="suggestList.length"
      class="absolute bg-weather-second text-white w-full shadow-md py-2 px-1 top-[62px]"
    >
      <li
        v-for="(item, index) in suggestList"
        :key="index"
        class="py-2 cursor-pointer"
        @click="handleRoute(item.adcode, item.cityNmae)"
      >
        {{ item.cityNmae }}
      </li>
    </ul>
  </div>
  <!-- 城市列表 -->
  <CityList />
  <!-- 天气信息 -->
  <h2 class="mt-6">近期天气</h2>
  <InfoChart :data="weatherInfo" />
</template>

<style scoped>
.focus\:border-input-fcous:focus {
  --tw-border-opacity: 1;
  border-color: rgb(0 78 113 / var(--tw-border-opacity));
}
</style>